import { Component, OnInit } from '@angular/core';
import { HttpClient, HttpRequest, HttpResponse } from '@angular/common/http';
import { NzMessageService } from 'ng-zorro-antd/message';
import { UploadFile } from 'ng-zorro-antd/upload';
import { filter } from 'rxjs/operators';

@Component({
  selector: 'app-manualupload',
  templateUrl: './manualupload.component.html',
  styleUrls: ['./manualupload.component.css']
})
export class ManualuploadComponent implements OnInit {

  uploading = false;
  fileList: UploadFile[] = [];

  ngOnInit() {
  }


  constructor(
    private http: HttpClient,
    private msg: NzMessageService) { }

  // 上传之前
  beforeUpload = (file: UploadFile): boolean => {
    // 将所有文件
    console.log(file)
    // concat 可以连接数组
    this.fileList = this.fileList.concat(file);
    console.log(this.fileList)
    return false;
  };

  handleUpload(): void {
    const formData = new FormData();
    console.log(formData)
    // tslint:disable-next-line:no-any
    this.fileList.forEach((file: any) => {
      formData.append('files[]', file);
    });
    console.log(formData)

    this.uploading = true;
    // You can use any AJAX library you like
    const req = new HttpRequest('POST', 'https://jsonplaceholder.typ333icode.com/posts/', formData, {
      // reportProgress: true
    });
    this.http
      .request(req)
      .pipe(filter(e => e instanceof HttpResponse))
      .subscribe(
        () => {
          this.uploading = false;
          console.log(this.fileList)
          this.fileList = [];
          this.msg.success('上传成功');
        },
        () => {
          this.uploading = false;
          this.msg.error('上传失败');
        }
      );
  }

  // nzChange(event ){
  //   console.log(event)
  //   // console.log(file)
  //   if(event.type=="start"){
  //     console.log("我开始上传了")
  //   }
  //   if(event.type=="progress"){
  //     console.log("我正在上传")
  //   }
  //   if(event.type=="error"){
  //     console.log("上传失败")
  //   }
  //   if(event.type=="success"){
  //     console.log("上传成功")
  //   }

  // }
}
